<template>
  <div id="app">
    <Header @addTodo="addTodo"/>
    <hr>
    <List  @removeItem="removeItem" @changeDone="changeDone" @remove="removeItem" :todos="todos"/>
    <hr>
    <Footer @showAll="showAll" @shoaDone="showDone" @showUndone="showUndone" :total="todos.length" @clearAll="clearAll"/>
  </div>
</template>

<script>
import Header from './components/header';
import List from './components/list';
import Footer from './components/footer';

export default {
  name: 'App',
  components: {
    Header,
    List,
    Footer,
  },
  watch: {
    todos(val) {
      localStorage.setItem('todos', JSON.stringify(val));
    },
  },
  mounted() {
    this.reload();
  },
  data() {
    return {
      todos: [],
    };
  },
  methods: {
    reload() {
      this.todos = [...JSON.parse(localStorage.getItem('todos'))];
    },
    showAll() {
      this.reload();
    },
    showDone() {
      this.todos = [...this.todos.filter(({checked}) => checked)];
    },
    showUndone() {
      this.todos = [...this.todos.filter(({checked}) => !checked)];
    },
    changeDone(id) {
      this.todos = this.todos.reduce((pre, item) => {
        if (item.id === id) {
          item.checked = !item.checked;
        }
        pre.push(item);
        return pre;
      }, []);
    },
    removeItem(id) {
      this.todos = this.todos.filter((item) => item.id !== id);
    },
    addTodo(content) {
      this.todos.unshift({
        id: Math.random().toString(36).slice(2),
        content,
        checked: false,
      });
    },
    clearAll() {
      this.todos = [];
    },
  },
};
</script>

<style scoped>
#app {
  display: flex;
  flex-direction: column;
}
</style>
